﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Implements methods common to single value list controls (lack of MI).
	/// </summary>
	public static class SingleValueListControlCommon
	{
		/// <summary>
		/// Gets the selected item.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="listControl"></param>
		/// <returns></returns>
		public static ListItem get_SelectedItem<T>(T listControl)
			where T : BaseValueControl<string>, ISingleValueListControl
		{
			if (string.IsNullOrEmpty(listControl.Value))
				return null;
			return listControl.Items.FindByValue(listControl.Value);
		}
		/// <summary>
		/// Sets the selected item.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="listControl"></param>
		/// <param name="value"></param>
		public static void set_SelectedItem<T>(T listControl, ListItem value)
			where T : BaseValueControl<string>, ISingleValueListControl
		{
			listControl.Value = value == null ? null : value.Value;
		}
		/// <summary>
		/// Gets the index of the selected item.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="listControl"></param>
		/// <returns></returns>
		public static int get_SelectedIndex<T>(T listControl)
			where T : BaseValueControl<string>, ISingleValueListControl
		{
			ListItem[] options = listControl.Options;
			for (int i = 0; i < options.Length; ++i)
			{
				if (string.Equals(options[i].Value, listControl.Value))
				{
					return i;
				}
			}
			return -1;
		}
		/// <summary>
		/// Sets the index of the selected item.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="listControl"></param>
		/// <param name="value"></param>
		public static void set_SelectedIndex<T>(T listControl, int value)
			where T : BaseValueControl<string>, ISingleValueListControl
		{
			if (value == -1)
				listControl.Value = null;
			else
				listControl.Value = listControl.Options[value].Value;
		}
	}
}
